package se.energimyndigheten.lampguiden;

import android.app.Activity;
import android.support.v4.app.Fragment;

/**
 * This interface help fragments to call their parent activity (that implements FragmentSwapper) to make fragment transitions.
 */
public abstract class SwappableFragment extends Fragment {
    protected FragmentSwapper mSwapper;

    protected void addFragmentSwapper(Activity swapper) {
        try {
            mSwapper = (FragmentSwapper) swapper;
        } catch (ClassCastException cce) {
            cce.printStackTrace();
        }
    }

    /**
     * Tell parent to swap this fragment for another.
     * @param fragment The new fragment to transition to
     * @param addToBackStack Should current fragment be added to back stack?
     */
    protected void swapFragment(Fragment fragment, boolean addToBackStack) {
        if (mSwapper == null) {
            addFragmentSwapper(getActivity());
        }
        mSwapper.swapFragment(fragment, addToBackStack);
    }

    /**
     * Call parent to set title
     * @param titleResource resource id of title string
     */
    protected void setTitle(int titleResource) {
        if (mSwapper == null) {
            addFragmentSwapper(getActivity());
        }
        mSwapper.setFragmentTitle(((Activity) mSwapper).getResources().getString(titleResource));
    }
}
